package com.competition.login.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.competition.commonutils.R;
import com.competition.login.entity.User;
import com.competition.login.service.SendEmailService;
import com.competition.login.service.UserService;
import com.competition.login.util.RandomCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/login/serviceMsm")
@Api(description = "发送验证码相关的接口")
public class SendEmailController {

    @Autowired
    private SendEmailService sendEmailService;

    @Autowired
    private UserService userService;

    @PostMapping("sendEmail")
    @ApiOperation("点击该接口，发送短信验证码，传递参数为用户邮箱")
    public R sendEmail(String email, HttpServletRequest request){

        QueryWrapper<User> userServiceQueryWrapper=new QueryWrapper<>();
        userServiceQueryWrapper.eq("email",email);
        List<User> userList = userService.list(userServiceQueryWrapper);
        if(userList.size()==0){
            return R.error().data("msg","亲，该账号不存者");
        }else{
            String verCode= RandomCodeUtil.getVerCode();
            //调用qq邮箱的方法，发送邮件
            request.getSession().removeAttribute("verCode");
            Boolean isSend=sendEmailService.sendAuthCodeEmail(email,verCode);
            if (isSend){//如果发送成功
                //发送成功，把验证码设置进session中,并且设置有效时间(30分钟)
                request.getSession().setAttribute("verCode",verCode);
                System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+request.getSession().getAttribute("verCode"));
                return R.ok().data("verCode",verCode);
            }
            return R.error();
        }

    }

}
